<template>
    <div class="app-container">
        <el-form
            class="searchForm"
            :inline="true"
            size="mini"
            ref="searchForm"
            :model="searchForm"
        >
            <el-form-item label="设备编码">
                <el-input
                    v-model="searchForm.equipCode"
                    placeholder="请输入设备编码"
                    clearable
                />
            </el-form-item>
            <el-form-item label="流水号">
                <el-input
                    v-model="searchForm.txnNo"
                    placeholder="请输入流水号"
                    clearable
                />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    style="width: 230px"
                    :append-to-body="false"
                    :popper-append-to-body="false"
                    v-model="rangeDate"
                    type="daterange"
                    align="right"
                    unlink-panels
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始创建时间"
                    end-placeholder="结束创建时间"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doSearch"
                    >搜索</el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetSearch"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <div class="searchs-content">
            <el-button
                v-permission="['om:imagextract:add']"
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                @click="addDialog"
                >新增</el-button
            >
        </div>

        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="curstatus" slot-scope="scope">
                <div class="codes">
                    <el-tag type="primary" v-if="scope.row.status === 1"
                        >发起成功</el-tag
                    >
                    <el-tag type="danger" v-else-if="scope.row.status === 2"
                        >发起失败</el-tag
                    >
                    <el-tag type="success" v-else-if="scope.row.status === 3"
                        >提取成功</el-tag
                    >
                    <span v-else>{{ scope.row.status }}</span>
                </div>
            </template>
            <template slot="action" slot-scope="scope">
                <el-button
                    type="primary"
                    size="mini"
                    @click="detailDialog(scope.row)"
                    >详情</el-button
                >
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 弹框 -->
        <Dialog
            :visible="addVisible"
            width="32%"
            :loading="dialogBtnLoading"
            title="新增"
            @confirmDialog="confirmDialog"
            @cancelDialog="cancelDialog"
        >
            <el-form
                ref="dialogForm"
                :model="dialogForm"
                label-width="110px"
                :rules="dialogRules" size="small"
            >
                <el-form-item label="设备编码" prop="equipCode">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="dialogForm.equipCode"
                        placeholder="请点击搜索自动回显设备编码"
                    >
                        <el-button
                            slot="append"
                            icon="el-icon-search"
                            @click="isShowCodeData"
                        ></el-button
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="操作指令"
                    required
                    prop="cameraExtractParam.value"
                >
                    <el-select
                        class="ipt"
                        v-model="dialogForm.cameraExtractParam.value"
                        placeholder="请选择操作指令"
                    >
                        <el-option
                            v-for="item in enumsJson.EQUIP_CAMERA_EXTRACT_LOG_TYPE"
                            :key="item.code"
                            :label="item.label"
                            :value="item.code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="提取日期"
                    prop="startDate"
                    :rules="
                        dialogForm.cameraExtractParam.value &&
                        dialogForm.cameraExtractParam.value != '0'
                            ? dialogRules.startDate
                            : []
                    "
                >
                    <el-date-picker
                        class="ipt"
                        v-model="dialogForm.startDate"
                        :disabled="dialogForm.cameraExtractParam.value == '0'"
                        :append-to-body="false"
                        :popper-append-to-body="false"
                        type="date"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择提取日期"
                        :picker-options="process"
                        @change="dateChange"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-link
                    type="danger"
                    :underline="false"
                    style="margin: 0 0 10px 40px"
                    >注：建议提取开始时间和结束时间不超过5分钟！！！
                </el-link>
                <el-form-item
                    label="提取时间"
                    prop="tractDate"
                    :rules="
                        dialogForm.cameraExtractParam.value &&
                        dialogForm.cameraExtractParam.value != '0'
                            ? dialogRules.tractDate
                            : []
                    "
                >
                    <el-time-picker
                        is-range
                        class="ipt"
                        v-model="dialogForm.tractDate"
                        :disabled="dialogForm.cameraExtractParam.value == '0'"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        placeholder="请选择提取时间"
                        @change="timesChange"
                    >
                    </el-time-picker>
                </el-form-item>
            </el-form>
        </Dialog>

        <!-- 详情 -->
        <Dialog
            :visible="detailVisible"
            width="32%"
            title="详情"
            :isFooter="false"
            @cancelDialog="closeDetailDialog"
        >
            <el-form ref="currentRow" :model="currentRow" label-width="110px" size="small">
                <el-form-item label="设备编码">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="currentRow.equipCode"
                    ></el-input>
                </el-form-item>
                <el-form-item label="设备ID">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="currentRow.equipId"
                    ></el-input>
                </el-form-item>
                <el-form-item label="交易流水">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="currentRow.txnNo"
                    ></el-input>
                </el-form-item>
                <el-form-item label="操作指令">
                    <el-select disabled class="ipt" v-model="currentRow.type">
                        <el-option
                            v-for="item in enumsJson.EQUIP_CAMERA_EXTRACT_LOG_TYPE"
                            :key="item.code"
                            :label="item.label"
                            :value="item.code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select disabled class="ipt" v-model="currentRow.status">
                        <el-option
                            v-for="item in enumsJson.EQUIP_CAMERA_EXTRACT_LOG_STATUS"
                            :key="item.code"
                            :label="item.label"
                            :value="item.code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="结果描述">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="currentRow.reasonName"
                    ></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="currentRow.createTime"
                    ></el-input>
                </el-form-item>
                <el-form-item label="接收时间">
                    <el-input
                        class="ipt"
                        readonly
                        v-model="currentRow.receiveTime"
                    ></el-input>
                </el-form-item>
                <el-form-item label="文件列表">
                    <span v-if="fileList.length == 0">暂无</span>
                    <el-progress
                        :percentage="percentage"
                        v-if="percentage < 100 && fileLoading"
                    ></el-progress>
                    <el-upload
                        action="#"
                        :file-list="fileList"
                        list-type="picture-card"
                        v-loading="fileLoading"
                        element-loading-text="正在下载，请稍等。"
                    >
                        <div slot="file" slot-scope="{ file }">
                            <img
                                v-if="file.type == 1"
                                class="el-upload-list__item-thumbnail"
                                :src="file.url"
                                alt=""
                            />
                            <span
                                v-if="file.type == 2"
                                style="display: inline-block; margin: 6px"
                                >{{ file.fileName }}</span
                            >
                            <video
                                v-if="file.type == 2"
                                :src="file.url"
                                style="width: 100%"
                            >
                                您的浏览器不支持 video 标签。
                            </video>

                            <span class="el-upload-list__item-actions">
                                <span
                                    v-if="file.type == 1"
                                    class="el-upload-list__item-preview"
                                    @click="handlePictureCardPreview(file)"
                                >
                                    <i class="el-icon-zoom-in"></i>
                                </span>

                                <span
                                    v-if="file.type == 2"
                                    class="el-upload-list__item-delete"
                                    @click="handleDownload(file)"
                                >
                                    <i class="el-icon-download"></i>
                                </span>
                            </span>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </Dialog>
        <el-dialog :visible.sync="fileVisible" width="50%">
            <img
                v-if="fileType == 1"
                class="el-upload-list__item-thumbnail"
                width="100%"
                :src="imageUrl"
                alt=""
            />
            <video
                v-if="fileType == 2"
                style="width: 100%"
                :src="imageUrl"
                controls
                autoplay
            >
                您的浏览器不支持 video 标签。
            </video>
        </el-dialog>

        <!-- 弹框 -->
        <Dialog
            :visible="visible"
            width="48%"
            class="equipFormDialog"
            title="勾选需要提取的设备"
            @confirmDialog="equipConfirmDialog"
            @cancelDialog="cancelEquipDialog"
        >
            <el-form
                class="filters equipForm"
                ref="equipForm"
                :model="equipForm"
                label-width="70px"
            >
                <el-form-item label="设备编码">
                    <el-input
                        style="width: 100%"
                        v-model="equipForm.code"
                        placeholder="请点击搜索选择设备编码"
                    />
                </el-form-item>
                <el-form-item label="设备id">
                    <el-input
                        v-model="equipForm.id"
                        placeholder="请输入设备id"
                    />
                </el-form-item>
                <div class="search-btns">
                    <el-button
                        type="primary"
                        size="mini"
                        icon="el-icon-search"
                        @click="searchCodeData"
                        >搜索</el-button
                    >
                    <el-button
                        type="default"
                        size="mini"
                        icon="el-icon-refresh"
                        @click="clearEquipData"
                        >重置</el-button
                    >
                </div>
            </el-form>
            <div class="table-box">
            <el-table
                :loading="codeListLoading"
                :data="equipCodeList"
                ref="tableDemand"
                style="width: 100%"
                stripe
            >
                <el-table-column
                    label="ID"
                    show-overflow-tooltip
                    prop="id"
                    min-width="40%"
                >
                    <template slot-scope="scope">
                        <el-radio
                            :disabled="!scope.row.isOnline"
                            :label="scope.row.id"
                            v-model="codeRadio"
                            @change.native="
                                handleSelectionChange(scope.$index, scope.row)
                            "
                            >&nbsp;</el-radio
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    prop="code"
                    label="设备编码"
                    min-width="40%"
                    show-overflow-tooltip
                ></el-table-column>

                <el-table-column
                    prop="isOnline"
                    label="是否在线"
                    min-width="15%"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.isOnline ? 'success' : 'danger'"
                            >{{ onlineType(scope.row.isOnline) }}</el-tag
                        >
                    </template>
                </el-table-column>
            </el-table>
            </div>
            <pagination
                v-if="equipTotal > 0"
                :total="equipTotal"
                :pageSizes="[10, 20, 30, 40, 50]"
                :page.sync="equipForm.pageNum"
                :limit.sync="equipForm.pageSize"
                @pagination="searchCodeData"
            />
        </Dialog>
    </div>
</template>

<script>
import { equipment } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";
import axios from "axios";
import { getToken } from "@/utils/auth";
export default {
    components: { Pagination, Table, Dialog },

    data() {
        const validateTimeRange = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请选择开始时间和结束时间"));
                return;
            }
            // 校验逻辑
            const startTime = value[0];
            const endTime = value[1];
            if (!startTime || !endTime) {
                // 如果开始时间和结束时间都未选择，则提示错误
                callback(new Error("请选择开始时间和结束时间"));
            } else {
                // 通过校验
                callback();
            }
        };
        return {
            listLoading: true,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                equipCode: "", //设备Code
                txnNo: "", //交易流水号
                startCreateTime: "", //开始创建时间
                endCreateTime: "", //结束创建时间
            },
            rangeDate: [],

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设备编码",
                    prop: "equipCode",
                    width: "115",
                },
                {
                    label: "设备ID",
                    prop: "equipId",
                },

                {
                    label: "交易流水号",
                    prop: "txnNo",
                    width:"80"
                },
                {
                    label: "类型",
                    prop: "type",
                    formatter: (item) => {
                        let classify =
                            this.enumsJson.EQUIP_CAMERA_EXTRACT_LOG_TYPE.find(
                                (p) => {
                                    return item.type != null
                                        ? item.type.toString() ==
                                              p.code.toString()
                                        : "";
                                }
                            );
                        return classify ? classify.label : "";
                    },
                    width:"70"
                },
                { slot: "curstatus", label: "状态" ,width:"90"},
                {
                    label: "结果描述",
                    prop: "reasonName",
                },
                {
                    label: "创建时间",
                    prop: "createTime",
                    width:"90"
                },
                {
                    label: "接收时间",
                    prop: "receiveTime",
                    width:"90"
                },
                { slot: "action", label: "操作", width: "100" },
            ],
            tableData: [],
            visible: false, //弹框标识
            dialogForm: {
                equipId: "",
                equipCode: "",
                tractDate: ["00:00:00", "00:05:00"],
                startDate: "",
                cameraExtractParam: {
                    value: "",
                    endTime: "",
                    startTime: "",
                },
            },
            dialogRules: {
                "cameraExtractParam.value": [
                    {
                        required: true,
                        message: "请选择操作指令",
                        trigger: "change",
                    },
                ],
                startDate: [
                    {
                        required: true,
                        message: "请选择提取日期",
                        trigger: "blur",
                    },
                ],
                tractDate: [
                    {
                        required: true,
                        validator: validateTimeRange,
                        trigger: "blur",
                    },
                ],
                equipCode: [
                    {
                        required: true,
                        message: "请点击搜索选择设备编码",
                        trigger: "change",
                    },
                ],
            },

            dialogBtnLoading: false,

            factureOption: [], //运营商
            uploading: false,
            enumsJson: {}, //枚举

            currentRow: {},
            IMGLink: this.IMGLink,
            addVisible: false,
            equipCodeList: [], //搜索设备列表
            codeRadio: "",
            currentCodeItem: {}, //当前选中设备项
            codeListLoading: false,
            equipTotal: 0,
            equipForm: {
                pageNum: 1,
                pageSize: 10,
                code: null,
                id: null,
            },

            imageUrl: "",
            detailVisible: false,
            fileList: [],
            fileVisible: false,
            fileType: null,

            fileLoading: false, //文件下载
            percentage: 0, //进度条的占比
        };
    },
    computed: {
        process() {
            const _this = this;
            return {
                disabledDate(time) {
                    return time.getTime() >= new Date().getTime();
                },
            };
        },
    },
    async created() {
        this.enumsJson = await this.$store.dispatch("enums/generateEnumMap");
        this.fetchData();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            this.tableData = [];
            this.total = 0;
            let param = { ...this.searchForm };
            if (this.rangeDate && this.rangeDate.length > 0) {
                param.startCreateTime = this.rangeDate[0];
                param.endCreateTime = this.rangeDate[1];
            }

            equipment(
                "/cameraextract/list",
                "post",
                { ...removeNullUndefined(param) },
                1
            )
                .then((res) => {
                    this.tableData = res.data;
                    this.total = +res.total;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },

        // 弹框取消
        cancelDialog() {
            this.addVisible = false;
            this.clearData();
            this.resetDialogForm("dialogForm");
        },
        clearData() {
            this.dialogForm = {
                equipId: "",
                equipCode: "",
                tractDate: ["00:00:00", "00:05:00"],
                startDate: "",
                cameraExtractParam: {
                    value: "",
                    endTime: "",
                    startTime: "",
                },
            };
        },
        // 弹框确认
        confirmDialog() {
            this.submitDialogForm("dialogForm");
        },
        // 新增
        async addDialog(row) {
            this.addVisible = true;
        },

        detailDialog(row) {
            this.detailVisible = true;
            this.currentRow = { ...row };
            this.fileList = row.files
                ? row.files.split(",").map((item) => {
                      return {
                          url: `${this.IMGLink}${item}`,
                          type: this.checkImg(item),
                          fileName:
                              item && item.slice(item.lastIndexOf("/") + 1),
                      };
                  })
                : [];
        },

        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    handleConfirm("确定要新增吗？", "warning", "提示")
                        .then((res) => {
                            this.doAdd();
                        })
                        .catch((err) => {});
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetDialogForm(formName) {
            this.$refs[formName].resetFields();
        },

        resetSearch() {
            this.rangeDate = [];
            this.searchForm = {
                pageNum: 1,
                pageSize: 15,
                equipCode: "", //设备Code
                txnNo: "", //交易流水号
                startCreateTime: "", //开始创建时间
                endCreateTime: "", //结束创建时间
            };
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },

        doAdd() {
            let { cameraExtractParam, equipId } = { ...this.dialogForm };
            let param =
                this.dialogForm.cameraExtractParam.value == "0"
                    ? {
                          cameraExtractParam: {
                              value: cameraExtractParam.value,
                          },
                          equipId: equipId,
                      }
                    : { cameraExtractParam, equipId };
            this.dialogBtnLoading = true;
            equipment("/cameraextract/insert", "post", param, 1)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success(res.message);
                        this.addVisible = false;
                        this.fetchData();
                    }
                })
                .finally(() => {
                    this.dialogBtnLoading = false;
                });
        },

        isShowCodeData() {
            this.visible = true;
            this.searchCodeData();
        },
        searchCodeData() {
            this.equipCodeList = [];
            this.equipTotal = 0;
            this.codeListLoading = true;
            equipment(
                "/info/list",
                "post",
                {
                    ...removeNullUndefined(this.equipForm),
                },
                1
            )
                .then((res) => {
                    this.equipCodeList = res.data;
                    this.equipTotal = +res.total;
                })
                .finally(() => (this.codeListLoading = false));
        },
        handleSelectionChange(index, row) {
            this.currentCodeItem = row;
        },
        cancelEquipDialog() {
            this.visible = false;
            this.clearEquipData();
        },
        clearEquipData() {
            this.equipForm = {
                pageNum: this.equipForm.pageNum,
                pageSize: this.equipForm.pageSize,
                code: null,
                id: null,
            };
            this.codeRadio = "";
        },
        onlineType(type) {
            let classify = this.enumsJson.IS_ONLINE.find((p) => {
                return p.code == type;
            });
            return classify ? classify.label : "";
        },
        equipConfirmDialog() {
            if (Object.keys(this.currentCodeItem).length == 0) {
                this.$message.error("请勾选需要提取的设备！");
                return;
            }
            this.visible = false;
            this.dialogForm.equipCode = this.currentCodeItem.code;
            this.dialogForm.equipId = this.currentCodeItem.id;
        },
        dateChange(e) {
            this.$refs.dialogForm.validateField("startDate");
            this.dateTimePicker();
        },
        timesChange(e) {
            this.$refs.dialogForm.validateField("tractDate");
            this.dateTimePicker();
        },
        dateTimePicker() {
            let startTime =
                this.dialogForm.tractDate &&
                this.dialogForm.tractDate.length > 0 &&
                this.dialogForm.startDate
                    ? this.dialogForm.startDate +
                      " " +
                      this.dialogForm.tractDate[0]
                    : null;
            let endTime =
                this.dialogForm.tractDate &&
                this.dialogForm.tractDate.length > 0 &&
                this.dialogForm.startDate
                    ? this.dialogForm.startDate +
                      " " +
                      this.dialogForm.tractDate[1]
                    : null;

            this.dialogForm.cameraExtractParam.startTime = startTime
                ? new Date(startTime).getTime()
                : "";
            this.dialogForm.cameraExtractParam.endTime = endTime
                ? new Date(endTime).getTime()
                : "";
        },
        handlePictureCardPreview(file) {
            this.fileVisible = true;
            this.imageUrl = file.url;
            this.fileType = file.type;
        },
        // 判断是否是图片格式 1图片 2视频
        checkImg(url) {
            let index = url.indexOf(".");
            let img_id = url.substring(index); //截断"."之前的，得到后缀
            if (
                img_id == ".bmp" ||
                img_id == ".png" ||
                img_id == ".gif" ||
                img_id == ".jpg" ||
                img_id == ".jpeg"
            ) {
                return 1;
            } else {
                return 2;
            }
        },
        handleDownload(file) {
            let url = file.url; // 下载文件的url
            let fileName = url.slice(url.lastIndexOf("/") + 1);
            // const link = document.createElement("a");
            // link.href = url;
            // link.download = fileName; // 下载文件的名称
            // link.click();
            if (url) {
                this.fileLoading = true;
                axios
                    .get(url, {
                        headers: { Authorization: getToken() },
                        responseType: "blob",
                        //xml返回数据的钩子函数，可以用来获取数据的进度 具体可查看axios的官网
                        onDownloadProgress: (progressEvent) => {
                            //progressEvent.loaded 下载文件的当前大小
                            //progressEvent.total  下载文件的总大小 如果后端没有返回 请让他加上！
                            let progressBar = Math.round(
                                (progressEvent.loaded / progressEvent.total) *
                                    100
                            );
                            //接收进度为99%的时候需要留一点前端编译的时间
                            if (progressBar >= 99) {
                                this.percentage = 99;
                            } else {
                                this.percentage = progressBar;
                            }
                        },
                    })
                    .then((response) => {
                        this.fileLoading = false;
                        //当前定义res.message 出现的时候说明后端文件返回出现了问题 不然应该直接是个文件流
                        if (response.message) {
                            this.$message.error('下载失败！');
                            return;
                        }
                        let blob = new Blob([response.data]);
                        let Url = URL.createObjectURL(blob); //生成一个url
                        const a = document.createElement("a");
                        a.href = Url;
                        a.download = fileName;
                        a.click();
                        window.URL.revokeObjectURL(Url);
                        //编译文件完成后，进度条展示为100%100
                        this.percentage = 100;
                        this.$message.success("下载完成！");
                    });
            } else {
                this.$message.error("文件路径错误，无法下载！");
            }
        },
        closeDetailDialog() {
            this.detailVisible = false;
            this.fileList = [];
            this.currentRow = {};
        },
    },
};
</script>

<style lang="scss" scoped>
.ipt {
    width: 96%;
}
.searchForm {
    padding-left: 8px;
    .el-form-item {
        margin-bottom: 8px;
    }
}
.filters {
    .el-form-item {
        width: 15%;
    }
    .el-form-item:nth-child(3) {
        width: 30%;
    }
}
.equipForm {
    .el-form-item {
        width: 30%;
    }
}
.equipFormDialog {
    ::v-deep .pagination-container {
        padding: 10px 0 0;
    }
}
::v-deep .el-upload--picture-card {
    display: none;
}
::v-deep .el-input.is-disabled .el-input__inner {
    color: #666666;
}
</style>
